//
//  StatusDAL.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/22.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import Foundation
private let maxCacheDateTime: NSTimeInterval = 60 * 60 * 24 * 7

class StatusDAL {
    /// 加载数据
    ///
    /// - parameter since_id: since_id
    /// - parameter max_id:   max_id
    /// - parameter finished: 返回数据
    class func loadStatus(since_id: Int, max_id: Int, finished:(array: [[String: AnyObject]]?)->()){
        //1.加载本地是否有缓存数据
       let array =  checkCache(since_id, max_id: max_id)
        //2.如果有,返回数据
        if array?.count > 0 {
//            print("查询到数据个数\(array?.count)")
            finished(array: array)
            return
        }
        // 3 如果没有加载网络数据
        print("加载网络数据")
        NetworkTools.onceToken.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print("网络家在出错")
                finished(array: nil)
                return
            }
            guard let array = result?["statuses"] as? [[String : AnyObject]] else{
                finished(array: nil)
                print("格式转化错误")
                return
            }
            // 4.将网络返回的数据保存到本地
            saveCache(array)
            // 5.返回网络数据
            finished(array: array)
        }
    }
    
    class func clearDateCache(){
        let date = NSDate(timeIntervalSinceNow: -maxCacheDateTime)
        let df = NSDateFormatter()
        df.locale = NSLocale(localeIdentifier: "en")
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = df.stringFromDate(date)
        let sql = "DELETE FROM T_Status WHERE createTime < ?;"
        SQliteManager.shareManager.queue.inDatabase { (db) -> Void in
            if db.executeUpdate(sql, dateStr){
                print("删除了\(db.changes)条数据)")
            }
            
        }
    }
    /// 保存网络加载的数据
    ///
    /// - parameter array: 传入需要保存的数据
    private class func saveCache(array:[[String: AnyObject]]){
        guard let userId = UserAccountVM.shareUserAccount.Account?.uid else{
            print("用户没有登录")
            return
        }
        let sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"
        SQliteManager.shareManager.queue.inTransaction { (db, rollBack) -> Void in
            for dict in array{
                let statusId = dict["id"] as! Int
                let json = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                if !db.executeUpdate(sql, statusId, json , userId){
                    print("插入数据失败")
                    rollBack.memory = true
                    break
                }
                
            }
            
            
        }
//        print("插入数据完成")
        
    }
    private class func checkCache(since_id: Int, max_id: Int)-> [[String: AnyObject]]?{
//        print("检查本地数据\(since_id)---\(max_id)")
        guard let userId =  UserAccountVM.shareUserAccount.Account?.uid else{
            return nil
        }
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId) \n"
        if since_id > 0 {
            sql += "    AND statusId > \(since_id) \n"
        }else if max_id > 0{
            sql += "    AND statusId < \(max_id) \n"
        }
        sql += "ORDER BY statusId DESC LIMIT 20;"
//        print("查询数据 SQL -> " + sql)
        
        let array = SQliteManager.shareManager.execRecordSet(sql)
        
        var arrayM = [[String: AnyObject]]()
        for dict in array{
            let jsonData = dict["status"] as! NSData
            
            let result = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
            arrayM.append(result as! [String : AnyObject])
        }
        return arrayM
    }
    
}